# ============================================================
# Appendix C — Conjoint: Immigration (Cell weights & Rake weights)
# Order:
# C1  Overall MM (cell)
# C2  Overall MM (rake)
# C3L Left MM (cell, non-interacted, left_pro_mig==1)
# C3R Right MM (cell, non-interacted, right_anti_mig==1)
# C4L Left MM interaction Ideology×Immigration (cell)
# C4R Right MM interaction Ideology×Immigration (cell)
# C5L Left MM (rake, non-interacted)
# C5R Right MM (rake, non-interacted)
# C6L Left MM interaction Ideology×Immigration (rake)
# C6R Right MM interaction Ideology×Immigration (rake)
# ============================================================

# ---- Paths ----
base_dir <- "~/Dropbox/Issue voting Chile"
data_dir <- file.path(base_dir, "09_replication/data")
fig_dir  <- file.path(base_dir, "09_replication/output")
dir.create(fig_dir, showWarnings = FALSE, recursive = TRUE)

# ---- Packages ----
library(tidyverse)
library(haven)
library(cregg)
library(ggplot2)
library(ggeasy)
library(dplyr)

# ---- Helpers ----
as_char <- function(x) as.character(as_factor(x))
save_fig <- function(filename, plot, width = 5, height = 5.4, dpi = 300) {
  ggsave(filename, plot = plot, width = width, height = height, dpi = dpi, bg = "white")
}
style_mm_plot <- function(p, title = NULL, x_limits = c(0, 1), x_breaks = seq(0, 1, 0.2),
                          title_size = 12, x_text = 10, y_text = 10) {
  p +
    theme_bw() +
    scale_color_manual(values = rep("black", 9)) +
    guides(color = "none") +
    theme(
      axis.text.x = element_text(size = x_text, color = "black"),
      axis.text.y = element_text(size = y_text, color = "black"),
      axis.title.x = element_blank()
    ) +
    scale_x_continuous(limits = x_limits, breaks = x_breaks) +
    labs(title = title) +
    easy_center_title() +
    theme(plot.title = element_text(size = title_size))
}

# ============================================================
# DATASETS
# d1: subsamples → 09_replication/data/wave2_conjoint.dta
# d2: overall    → 01_data/clean_data/wave2_conjoint_merged.dta
# ============================================================

# ---- d1: subsamples ----
d1 <- read_dta(file.path(data_dir, "wave2_conjoint.dta"))
atr1 <- c("a_1","a_2","a_3","a_4","a_5","a_6")
d1[, atr1] <- lapply(d1[, atr1], factor)

d1 <- d1 %>%
  mutate(
    Ideology    = a_1,
    Gender      = a_2,
    Age         = a_3,
    Feminism    = a_4,
    Immigration = a_5,
    Crime       = a_6
  )

# Baseline levels for d1
d1$Ideology    <- factor(d1$Ideology,    levels = c("Right","Left"))
d1$Feminism    <- factor(d1$Feminism,    levels = c("Non-Feminist","Feminist"))
d1$Crime       <- factor(d1$Crime,       levels = c("No Harsher Punishment","Harsher Punishment"))
d1$Immigration <- factor(d1$Immigration, levels = c("No Restrictions","New Immigration Restrictions"))

# Label recodes for plots (d1)
d1 <- d1 %>%
  mutate(
    Immigration = recode(Immigration, "New Immigration Restrictions" = "New Restrictions"),
    Crime = recode(Crime,
                   "No Harsher Punishment" = "Less Punitive",
                   "Harsher Punishment"    = "More Punitive")
  )

# ---- d2: overall ----
d2 <- read_dta("~/Dropbox/Issue voting Chile/01_data/clean_data/wave2_conjoint_merged.dta")
atr2 <- c("a_1_wave2","a_2_wave2","a_3_wave2","a_4_wave2","a_5_wave2","a_6_wave2")
d2[, atr2] <- lapply(d2[, atr2], factor)

d2$Ideology    <- d2$a_1_wave2
d2$Gender      <- d2$a_2_wave2
d2$Age         <- d2$a_3_wave2
d2$Feminism    <- d2$a_4_wave2
d2$Immigration <- d2$a_5_wave2
d2$Crime       <- d2$a_6_wave2

# Baseline levels for d2
d2$Ideology    <- factor(d2$Ideology,    levels = c("Right","Left"))
d2$Feminism    <- factor(d2$Feminism,    levels = c("Non-Feminist","Feminist"))
d2$Crime       <- factor(d2$Crime,       levels = c("No Harsher Punishment","Harsher Punishment"))
d2$Immigration <- factor(d2$Immigration, levels = c("No Restrictions","New Immigration Restrictions"))

# Recodes for plots (d2)
d2 <- d2 %>%
  mutate(
    Immigration = recode(Immigration, "New Immigration Restrictions" = "New Restrictions"),
    Crime = recode(Crime,
                   "No Harsher Punishment" = "Less Punitive",
                   "Harsher Punishment"    = "More Punitive")
  )

# ============================================================
# C1 — Marginal means (Cell weights) — uses d2
# ============================================================
m2 <- choice_clean2_wave2 ~ Ideology + Gender + Age + Feminism + Immigration + Crime
mm_all_wcell <- cj(
  data    = d2,
  formula = m2,
  id      = ~ numericalid_wave2,
  weights = ~ weight_joint,
  estimate = "mm"
)

plot_c1 <- plot(mm_all_wcell, vline = 0.5) +
  ggplot2::theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = FALSE) +
  labs(title = "C1. Marginal Means — Cell Weights") +
  easy_center_title() +
  theme(
    axis.text.x = element_text(size = 12, color = "black"),
    axis.text.y = element_text(size = 10, color = "black"),
    axis.title.x = element_blank()
  ) +
  scale_x_continuous(limits = c(0.3, 0.7), breaks = c(0.3, 0.4, 0.5, 0.6, 0.7))

save_fig('~/Dropbox/Issue voting Chile/05_figures/mm_all_wcell.png', plot_c1)

# ============================================================
# C2 — Marginal means (Rake weights) — uses d2
# ============================================================
mm_all_wrake <- cj(
  data    = d2,
  formula = m2,
  id      = ~ numericalid_wave2,
  weights = ~ weight_rake,
  estimate = "mm"
)

plot_c2 <- plot(mm_all_wrake, vline = 0.5) +
  ggplot2::theme_bw() +
  scale_color_manual(values = rep("black", 9)) +
  guides(color = FALSE) +
  labs(title = "C2. Marginal Means — Rake Weights") +
  easy_center_title() +
  theme(
    axis.text.x = element_text(size = 12, color = "black"),
    axis.text.y = element_text(size = 10, color = "black"),
    axis.title.x = element_blank()
  ) +
  scale_x_continuous(limits = c(0.3, 0.7), breaks = c(0.3, 0.4, 0.5, 0.6, 0.7))

save_fig('~/Dropbox/Issue voting Chile/05_figures/mm_all_wrake.png', plot_c2)

# ============================================================
# C3 Left — MM Ideology & Immigration (Cell weights) — d1 (left_pro_mig)
# ============================================================
left_pro_mig <- subset(d1, left_pro_mig == 1)
mm_left_mig_non_w1 <- mm(
  left_pro_mig,
  choice_clean2 ~ Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_joint
)

plt_c3_left <- plot(mm_left_mig_non_w1[c(1,2,10,11), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c3_left <- style_mm_plot(
  plt_c3_left,
  title = "C3 (Left). MM — Ideology & Immigration — Cell Weights (Left Pro-Immigration Subsample)"
)
save_fig(file.path(fig_dir, "mm_left_mig_non_weight1.png"), plt_c3_left)

# ============================================================
# C3 Right — MM Ideology & Immigration (Cell weights) — d1 (right_anti_mig)
# ============================================================
right_mig_non <- subset(d1, right_anti_mig == 1)
mm_right_mig_non_w1 <- mm(
  right_mig_non,
  choice_clean2 ~ Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_joint
)

plt_c3_right <- plot(mm_right_mig_non_w1[c(1,2,10,11), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c3_right <- style_mm_plot(
  plt_c3_right,
  title = "C3 (Right). MM — Ideology & Immigration — Cell Weights (Right Anti-Immigration Subsample)"
)
save_fig(file.path(fig_dir, "mm_right_mig_non_weight1.png"), plt_c3_right)

# ============================================================
# C4 Left — Interaction Ideology×Immigration (Cell weights) — d1
# ============================================================
left_pro_mig_int <- subset(d1, left_pro_mig == 1)
left_pro_mig_int$profile1 <- interaction(left_pro_mig_int$Ideology, left_pro_mig_int$Immigration, sep = "_")

mm_left_mig_w1 <- mm(
  left_pro_mig_int,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_joint
)
mm_left_mig_w1$feature <- ifelse(mm_left_mig_w1$feature == "profile1", "Ideology*Immigration", mm_left_mig_w1$feature)

plt_c4_left <- plot(mm_left_mig_w1[c(1,3,4,2), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c4_left <- style_mm_plot(
  plt_c4_left,
  title = "C4 (Left). Interaction — Ideology × Immigration — Cell Weights (Left Subsample)"
)
save_fig(file.path(fig_dir, "mm_left_mig_weight1.png"), plt_c4_left)

# ============================================================
# C4 Right — Interaction Ideology×Immigration (Cell weights) — d1
# ============================================================
d1$Ideology <- factor(d1$Ideology, levels = c("Left","Right"))  # order for right panel
right_mig_int <- subset(d1, right_anti_mig == 1)
right_mig_int$profile1 <- interaction(right_mig_int$Ideology, right_mig_int$Immigration, sep = "_")

mm_right_mig_w1 <- mm(
  right_mig_int,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_joint
)
mm_right_mig_w1$feature <- ifelse(mm_right_mig_w1$feature == "profile1", "Ideology*Immigration", mm_right_mig_w1$feature)

plt_c4_right <- plot(mm_right_mig_w1[c(1,3,2,4), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c4_right <- style_mm_plot(
  plt_c4_right,
  title = "C4 (Right). Interaction — Ideology × Immigration — Cell Weights (Right Subsample)"
)
save_fig(file.path(fig_dir, "mm_right_mig_weight1.png"), plt_c4_right)

# ============================================================
# C5 Left — MM Ideology & Immigration (Rake weights) — d1
# ============================================================
d1$Ideology <- factor(d1$Ideology, levels = c("Right","Left"))
left_pro_mig <- subset(d1, left_pro_mig == 1)
mm_left_mig_non_w2 <- mm(
  left_pro_mig,
  choice_clean2 ~ Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_rake
)

plt_c5_left <- plot(mm_left_mig_non_w2[c(1,2,10,11), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c5_left <- style_mm_plot(
  plt_c5_left,
  title = "C5 (Left). MM — Ideology & Immigration — Rake Weights (Left Pro-Immigration Subsample)"
)
save_fig(file.path(fig_dir, "mm_left_mig_non_weight2.png"), plt_c5_left)

# ============================================================
# C5 Right — MM Ideology & Immigration (Rake weights) — d1
# ============================================================
d1$Ideology <- factor(d1$Ideology, levels = c("Left","Right"))
right_mig_non <- subset(d1, right_anti_mig == 1)
mm_right_mig_non_w2 <- mm(
  right_mig_non,
  choice_clean2 ~ Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_rake
)

plt_c5_right <- plot(mm_right_mig_non_w2[c(1,2,10,11), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c5_right <- style_mm_plot(
  plt_c5_right,
  title = "C5 (Right). MM — Ideology & Immigration — Rake Weights (Right Anti-Immigration Subsample)"
)
save_fig(file.path(fig_dir, "mm_right_mig_non_weight2.png"), plt_c5_right)

# ============================================================
# C6 Left — Interaction Ideology×Immigration (Rake weights) — d1
# ============================================================
d1$Ideology <- factor(d1$Ideology, levels = c("Right","Left"))
left_pro_mig_int <- subset(d1, left_pro_mig == 1)
left_pro_mig_int$profile1 <- interaction(left_pro_mig_int$Ideology, left_pro_mig_int$Immigration, sep = "_")

mm_left_mig_w2 <- mm(
  left_pro_mig_int,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_rake
)
mm_left_mig_w2$feature <- ifelse(mm_left_mig_w2$feature == "profile1", "Ideology*Immigration", mm_left_mig_w2$feature)

plt_c6_left <- plot(mm_left_mig_w2[c(1,3,4,2), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c6_left <- style_mm_plot(
  plt_c6_left,
  title = "C6 (Left). Interaction — Ideology × Immigration — Rake Weights (Left Subsample)"
)
save_fig(file.path(fig_dir, "mm_left_mig_weight2.png"), plt_c6_left)

# ============================================================
# C6 Right — Interaction Ideology×Immigration (Rake weights) — d1
# ============================================================
d1$Ideology <- factor(d1$Ideology, levels = c("Left","Right"))
right_mig_int <- subset(d1, right_anti_mig == 1)
right_mig_int$profile1 <- interaction(right_mig_int$Ideology, right_mig_int$Immigration, sep = "_")

mm_right_mig_w2 <- mm(
  right_mig_int,
  choice_clean2 ~ profile1 + Ideology + Gender + Age + Feminism + Immigration + Crime,
  id = ~ numericalid, weights = ~ weight_rake
)
mm_right_mig_w2$feature <- ifelse(mm_right_mig_w2$feature == "profile1", "Ideology*Immigration", mm_right_mig_w2$feature)

plt_c6_right <- plot(mm_right_mig_w2[c(1,3,2,4), ], vline = 0.5) +
  scale_y_discrete(labels = c(
    "Left_No Restrictions"   = "Left and No New Restrictions",
    "Left_New Restrictions"  = "Left and New Restrictions",
    "Right_No Restrictions"  = "Right and No Restrictions",
    "Right_New Restrictions" = "Right and New Restrictions"
  ))
plt_c6_right <- style_mm_plot(
  plt_c6_right,
  title = "C6 (Right). Interaction — Ideology × Immigration — Rake Weights (Right Subsample)"
)
save_fig(file.path(fig_dir, "mm_right_mig_weight2.png"), plt_c6_right)
